
import HomePage_ModalComponent_NormalFooterComponent from "../../../../../../component/modal/component/normalFooter"
import HomePage_ModalComponent_HeaderNormalComponent from "../../../../../../component/modal/component/headerNormal"
import { Fragment, useEffect, useRef, useState } from "react"
import { $EventBus_off, $EventBus_on } from "../../../../../../../../common/utils"
import { asBlob } from 'html-docx-js-typescript';
import { saveAs } from "file-saver"
import HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent from "./component/dynamicsText"
import HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_ChartComponent from "./component/chart"
import HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_TableComponent from "./component/table"
import * as echarts from "echarts";
import "./index.css"
// 主页-数据维护页面-定检数据维护页面-新增或编辑弹窗组件
interface componentInterface {
    sourceData: object
    change_cancel: Function
}
const HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent: React.FC<componentInterface> = (props) => {
    // 用于存储图表的 ref
    const [mainSourceList, setMainSourceList] = useState<Array<Array<object>>>([])
    const [lineSourceList, setLineSourceList] = useState<Array<object>>([])
    const mainChartList = [
        {
            label: "变高中性点直流（A）",
            key: "dc",
        },
        {
            label: "噪声（dB）",
            key: "ni",
        },
        {
            label: "振动（mm/s）",
            key: "va",
        },
    ]
    const mainColumnList = [
        {

            title: `信号`,
            dataIndex: "title",
            color: "#3D3D3D",
        },
        {

            title: '最大值',
            dataIndex: 'max',
            color: "#096DD9"
        },
        {

            title: '最小值',
            dataIndex: 'min',
            color: "#096DD9"
        },
        {
            title: '平均值',
            dataIndex: 'mean',
            color: "#096DD9"
        },
    ]
    const lineColumnList = [
        {

            title: `名称`,
            dataIndex: "title",
            color: "#096DD9"
        },
        {

            title: '最大值/A',
            dataIndex: 'max',
            color: "#096DD9"
        },
        {

            title: '最小值/A',
            dataIndex: 'min',
            color: "#096DD9"
        },
        {
            title: '平均值/A',
            dataIndex: 'mean',
            color: "#096DD9"
        },
    ]

    const change_delete = () => {


    }
    const make_sourceList = () => {

        props.sourceData["main"]?.forEach((item: object) => {
            mainSourceList.push(
                [
                    {
                        title: "中性点电流(A)",
                        max: item["dcMax"],
                        min: item["dcMin"],
                        mean: item["dcMean"],
                    },
                    {
                        title: "噪声(dB)",
                        max: item["niMax"],
                        min: item["niMin"],
                        mean: item["niMean"],
                    },
                    {
                        title: "振动(mm/s)",
                        max: item["vaMax"],
                        min: item["vaMin"],
                        mean: item["vaMean"],
                    },
                ]
            )
        });
        props.sourceData["line"]?.forEach((item: object) => {
            lineSourceList.push(

                {
                    title: item["name"],
                    max: item["max"],
                    min: item["min"],
                    mean: item["mean"],
                }

            )
        });
        setMainSourceList([...mainSourceList])
        setLineSourceList([...lineSourceList])
    }
    // 广播函数数据
    const eventBusFuncData = {
        // 提交操作

        submitOperation: async (data: object) => {
            if (document.getElementById('main')) {

                // 1.遍历所有图表的 ID
                const mainChartIDList: Array<string> = []
                const lineChartIDList: Array<string> = []
                mainSourceList.forEach((_, idx) => {
                    mainChartIDList.push(
                        ...[
                            `${idx}mainEchart0`,
                            `${idx}mainEchart1`,
                            `${idx}mainEchart2`,
                        ]
                    )

                });
                lineSourceList.forEach((_, idx) => {
                    lineChartIDList.push(`${idx}LineEchart`,)
                });
                [...mainChartIDList, ...lineChartIDList].forEach((item) => {
                    const chartDom = document.getElementById(item);
                    if (chartDom) {
                        const chart = echarts.getInstanceByDom(chartDom);
                        if (chart) {
                            // 将图表转换为图片
                            const chartImage = chart.getDataURL({
                                type: 'png',
                                pixelRatio: 2,
                                // backgroundColor: '#fff',
                            });

                            // 创建图片元素并替换
                            const img = document.createElement('img');
                            img.src = chartImage;
                            if (item.includes("main")) {
                                img.width = 315; // 设置图片宽度
                                img.height = 320; // 设置图片高度自适应 
                            } else if (item.includes("Line")) {
                                img.width = 940; // 设置图片宽度
                                img.height = 320; // 设置图片高度自适应 

                            }
                            chartDom.parentNode?.replaceChild(img, chartDom);
                        }
                    }
                })
                //  克隆 DOM 节点  
                const element = document.getElementById('main')?.cloneNode(true) as HTMLElement;
                // 2. 获取所有样式  
                const styleSheets = Array.from(document.styleSheets);

                // 3. 循环处理所有元素，将 CSS 样式内联到元素中  
                const allElements = element.querySelectorAll('*');
                allElements.forEach((el: any) => {
                    styleSheets.forEach(styleSheet => {
                        try {
                            const rules = styleSheet.cssRules || styleSheet.rules;
                            if (rules) {
                                Array.from(rules).forEach(rule => {
                                    // 检查 rule 是否是 CSSStyleRule 的实例  
                                    if (rule instanceof CSSStyleRule) {
                                        if (el.matches(rule.selectorText)) {
                                            // 将匹配的 CSS 属性内联到元素 style 属性中  
                                            for (let i = 0; i < rule.style.length; i++) {
                                                const propertyName = rule.style[i];
                                                el.style[propertyName] = rule.style.getPropertyValue(propertyName);
                                            }
                                        }
                                    }
                                });
                            }
                        } catch (error) {
                            // 处理跨域样式表  
                            console.warn('无法访问跨域样式表:', styleSheet.href, error);
                        }
                    });
                });

                // 移除所有 class 属性，因为样式已经内联  
                allElements.forEach(el => {
                    el.removeAttribute('className');
                });

                try {
                    // 重新获取更新后的 DOM
                    const htmlString = element.outerHTML;
                    const converted = await asBlob(htmlString, {
                        orientation: 'landscape',
                        margins: { top: 800, right: 800, bottom: 800, left: 800 },
                    });

                    if (!converted) {
                        console.error('Failed to generate Blob object');
                        return;
                    }

                    saveAs(converted, 'report.docx');
                } catch (error) {
                    console.error('Error generating Word document:', error);
                }
            }
        }

    }

    useEffect(() => {
        make_sourceList()
    }, [props.sourceData])
    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])
    return (
        <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent">
            <HomePage_ModalComponent_HeaderNormalComponent name="报告详情" padding="15px 24px" change_cancel={props.change_cancel} />
            <main id="main" className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main">
                <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__title">
                    <div className="main-title__text">
                        <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["stationName"]} fontSize={16} fontWeight={600} marginLeft={0} marginRight={8} />
                        <span>评估报告</span>
                    </div>
                    <div className="main-title__dateTime">{props.sourceData["dateNumRange"]}</div>
                </div>

                {
                    props.sourceData["main"]?.map((item, idx) => (
                        <Fragment key={`main${idx}`}>
                            <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__describe">
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["alterName"]} marginLeft={0} />于
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["dateStrRange"]} />对
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["stationName"]} />
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={item["name"]} />主变进行了变高中性点直流、噪声、振动多参量同步监测。
                            </div>
                            <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__chart">
                                {
                                    mainChartList.map((chartItem, chartIdx) => (
                                        <Fragment key={`${idx}mainChart${chartIdx}`}>
                                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_ChartComponent id={`${idx}mainEchart${chartIdx}`} width={315} height={320} title={chartItem["label"]} sourceData={item[chartItem["key"]]} />
                                        </Fragment>
                                    ))
                                }
                            </div>
                            <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__describe">
                                根据对<HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["stationName"]} />测试结果可以分析得出，测试时间区间内
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={item["name"]} />主变变高中性点电流均值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["dcMean"]} A`} />,该段时间内中性点电流流出最大值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["dcOutMax"]} A`} />,流入最大值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["dcInMax"]} A`} />。该段时间内
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={item["name"]} />主变噪声均值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["niMean"]} mm/s`} />,最大值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["niMax"]} mm/s`} />,最小值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["niMin"]} mm/s`} />，该段时间内
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={item["name"]} />主变振动强度均值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["vaMean"]} dB`} />,最大值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["vaMax"]} dB`} />,最小值为
                                <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${item["vaMin"]} dB`} />。
                            </div>
                            <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__smallTitle">测试数据统计值</div>
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_TableComponent columnList={mainColumnList} sourceList={mainSourceList[idx]} />
                        </Fragment>
                    ))

                }
                <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__describe">
                    <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["stationName"]} marginLeft={0} />电缆层测试对象为
                    <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["lineName"]}/>，测试时间为
                    <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["dateStrRange"]} />，实测波形如下图所示。
                </div>
                {
                    props.sourceData["line"]?.map((item: object, idx: number) => (
                        <Fragment key={`line${idx}`}>
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_ChartComponent id={`${idx}LineEchart`} width={940} height={320} title={`${item["name"]}波形（A）`} sourceData={item} />
                        </Fragment>
                    ))

                }
                {
                    props.sourceData["line"]?.length && <>
                        <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__smallTitle">电缆层电流数值统计值</div>
                        <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_TableComponent columnList={lineColumnList} sourceList={lineSourceList} />
                        <div className="homePageStatisticalQueryPageAssessmentReportPageSeeModalComponent-main__describe">
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["lineMaxName"]} marginLeft={0} />测到的电流幅值最大，正向最大值达到
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMaxNameOutMax"]} A`} />，负向最大值达到
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMaxNameInMax"]} A`} />，取绝对值后的平均值为
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMaxNameMean"]} A`} />。
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={props.sourceData["lineMinName"]} />测到的电流幅值最小，正向最大值达到
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMinNameOutMax"]} A`}  />，负向最大值达到
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMinNameInMax"]} A`}  />，取绝对值后的平均值为
                            <HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent_DynamicsTextComponent text={`${props.sourceData["lineMinNameMean"]} A`}  />。
                        </div>
                    </>
                }
            </main>
            <HomePage_ModalComponent_NormalFooterComponent cancelName="删除" submitName="下载" change_cancel={change_delete} />
        </div>
    )
}
export default HomePage_StatisticalQueryPage_AssessmentReportPage_SeeModalComponent